package edu.spsu.mail;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.sun.mail.util.MailSSLSocketFactory;

public class ViewMailActivity extends ListActivity {
	
	private static final String TAG = ViewMailActivity.class.getName();

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		
	}

	@Override
	protected void onStart() {
		
		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = li.inflate(R.layout.main, null);
		
		new AlertDialog.Builder(this)
		.setTitle(R.string.hello)
		.setView(view)
		.setNeutralButton(R.string.login, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {

				EditText et0 = (EditText)view.findViewById(R.id.username);
				EditText et1 = (EditText)view.findViewById(R.id.password);
					
				String etu = et0.getText().toString();
				String etp = et1.getText().toString();
					
				setUpMessages(etu +"@spsu.edu", etp);
			}
		})
		.show();
		super.onStart();
	}

	@Override
	protected void onDestroy() {

		// Close connection 
		try {
			folder.close(false);
			store.close();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		String item = (String) getListAdapter().getItem(position);
		Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
	}

	private void setUpMessages(final String user, final String pass) {
		
		runOnUiThread(new Thread() {
			
			@Override
			public void run() {

				if (user != "" && pass != "") {
					
					Properties props = new Properties();
					props.setProperty("mail.store.protocol", "imaps");
					props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
					
					props.setProperty("mail.imaps.socketFactory.fallback", "false");
					props.setProperty("mail.imaps.ssl.enable", "true");
					
					props.setProperty("mail.imaps.ssl.trust", "zimbra.spsu.edu");
					props.setProperty("mail.imaps.socketFactory.host", "zimbra.spsu.edu");
					
					props.setProperty("mail.imaps.socketFactory.port", Integer.toString(993));
					props.setProperty("mail.imaps.timeout", Integer.toString(45000));
					
					props.setProperty("mail.imaps.connectionpooltimeout", Integer.toString(45000));
					props.setProperty("mail.imaps.connectiontimeout", Integer.toString(45000));
					
					try {

						MailSSLSocketFactory sf = new MailSSLSocketFactory();
						sf.setTrustAllHosts(true);

						props.put("mail.imaps.ssl.socketFactory", sf);
						session = Session.getInstance(props);

						store = session.getStore();
						store.connect("zimbra.spsu.edu", 993, user, pass);
						Toast.makeText(ViewMailActivity.this, String.format(
								"E-mail \"%s\" is valid", user),Toast.LENGTH_LONG).show();

						// Get folder
						folder = store.getFolder("INBOX");
						folder.open(Folder.READ_ONLY);

						int message_list_size = 3;

						// Get directory
						Message[] message = folder.getMessages();
						preface = new String[message_list_size];

						for (int i = message.length - 1; i > message.length
								- message_list_size - 1; i--) {
							preface[message.length - 1 - i] = (message[i]
									.getSubject() + "\n\t\tFrom:\t" + message[i]
									.getFrom()[0]);
						}

						ArrayAdapter<String> adapter = new ArrayAdapter<String>(ViewMailActivity.this, android.R.layout.simple_list_item_1, preface);
						setListAdapter(adapter);

					} catch (Exception ex) {

						String msg = String.format(
								"E-mail \"%s\" tested failed:\n\"%s\"", user, ex);

						Log.d(TAG, msg);

						Toast.makeText(ViewMailActivity.this, msg,
								Toast.LENGTH_LONG).show();
					}
				}
			}

		});
	}

	private String[] preface = new String[]{ "No Messages available." };
	private Session session;
	private Folder folder;
	private Store store;
}
